<template>
    <span >
        <region-list class="handle-select" @changeRegion="changeRegion" :region="query.regionId"></region-list>
        <el-select class="handle-select" v-model="deptId" @change="changeDept" placeholder="请选择部门" clearable>
            <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
        </el-select>
    </span>
</template>
<script>
import RegionList  from "./RegionList.vue"
import {getDeptByCondition} from "../../api/dept"
import {findByDept} from "../../api/region"

export default {
    name:"RegionDeptList",
    components: {
        RegionList
    },
    props: ['pdept'],
    data () {
        return {
            query:{
                regionId:'',
                pageNum:1,
                pageSize:5,

            },
            depts:[],
            deptId:this.pdept
        }
    },
    created () {
        if(this.pdept){
           this.refreshRegionDeptListByDept(this.pdept); //页面一创建，就要刷新联动列表。
       }
    },
    methods: {
        refreshRegionDeptListByDept(val){
             findByDept(val).then(resp=>{
                this.query.regionId = resp.data.regionId
                 getDeptByCondition(this.query).then(resp=>{
                    this.depts = resp.data.list
                })
            })
        },
        changeRegion(val){
            this.query.regionId = val
            this.deptId = ''
            getDeptByCondition(this.query).then(resp=>{
                this.depts = resp.data.list
            })
        },
        changeDept(val){
            this.$emit("changeDept",val);
        }
    },
    watch: {
        pdept(val){
            console.log("子组件中dept的值发生变化。。。。",val)
            this.deptId = val;
            if(val){
                this.refreshRegionDeptListByDept(val); //一旦部门信息发生变化，联动的下拉列表值也要发生变化。
            }else{
                this.query.regionId=''  //如果用户没有所属部门，之前选中的区域信息也应该清空。
            }
        }
    }
}
</script>
<style scoped>
.handle-select {
    width: 150px;
    margin: 3px;
}
</style>